function Util(){  		
	//////////////////////////////////////
	// HTML insertion
	this.insertHTML=function(elem,htmlStr,pos) {
		if(typeof(elem)=="string") elem=document.getElementById(elem);
		if(!pos)
			elem.innerHTML=htmlStr;
		else if(pos=="start")
			elem.innerHTML=htmlStr+elem.innerHTML;
		else if(pos=="end")
			elem.innerHTML=elem.innerHTML+htmlStr;
	};
	this.insertHTMLAtTopOf=function(elem,htmlStr) {
		this.insertHTML(elem,htmlStr,"top");
	};
	this.insertHTMLAtBottomOf=function(elem,htmlStr) {
		this.insertHTML(elem,htmlStr,"bottom");
	};
	//////////////////////////////////////
	// Toggle display/visibility styles
	this.toggleDisplay=function(elem,displayStyle) {
		if(typeof(elem)=="string") elem=document.getElementById(elem);
		elem.style.display=displayStyle;
	};
	this.toggleVisibility=function(elem,visibilityStyle) {
		if(typeof(elem)=="string") elem=document.getElementById(elem);
		elem.style.visibility=visibilityStyle;
	};
	//////////////////////////////////////
	// Add/remove specified classname to/from element
	this.addClassNameTo=function(elem,className) {
		if(typeof(elem)=="string") elem=document.getElementById(elem);
		var currClassName=elem.className;
		var patternToCheck=new RegExp("\w?"+className);
		if(!currClassName.match(patternToCheck))
			elem.className=(currClassName.length>=1)? currClassName+" "+className:className;
	};
	this.removeClassNameFrom=function(elem,className) {
		if(typeof(elem)=="string") elem=document.getElementById(elem);
		if(typeof(className)!="object") className=[className];
		var currClassName=elem.className;
		for(var i=0; i<className.length; i++) {
			var patternToRemove=new RegExp("\w?"+className[i],"g");
			elem.className=currClassName.replace(patternToRemove,"");
		}
	};
	this.removeChildren=function(elem) {
		if ( elem.hasChildNodes() )
		{
		    while ( elem.childNodes.length >= 1 )
		    {
		        elem.removeChild( elem.firstChild );       
		    } 
		}
	}
	this.dateDiff=function(pdate) { // Works with youtube dates only
		pdate = pdate.split("T");
		pdate = pdate[0].split("-"); // Split provided date and convert into date()
		var today = new Date()
		var olddate = new Date(pdate[0], pdate[1], pdate[2]);
		var one_day=1000*60*60*24; //Set 1 day in milliseconds
		
		//console.log(today.getTime()+" | "+olddate.getTime()+" | "+one_day);
		
		//Calculate difference btw the two dates, and convert to days
		return Math.ceil((today.getTime()-olddate.getTime())/(one_day));
	}
}

var Pagination = {
	numPerPage: 15,
	//not tested with EVEN numbers for page links
	numPageLinks: 3,
	numPages: 1,
	currentPage: 1,
	pageLinks: [],
	numResults: 0,	
	setVars: function(NumPerPage, NumPageLinks, CurrentPage, NumResults) {
		this.numPerPage = NumPerPage;
		this.numPageLinks = NumPageLinks;
		this.currentPage = CurrentPage;
		this.numResults = NumResults;
		//get number of pages
		this.numPages = Math.ceil(this.numResults/this.numPerPage);
	},
	_getCurrentPageIndexInPageLinks: function() {
		return ( Math.ceil(this.numPageLinks/2) -1 );
	},
	getPageLinks: function() {
		var returnarray = [];
		
		if(this.numPages < this.numPageLinks) {
			for(var i = 1; i < (this.numPages + 1); i++) {
				returnarray.push(i);
			}
		} else if(this.currentPage < (this._getCurrentPageIndexInPageLinks() + 1)) {
			for(var i = 1; i < (this.numPageLinks + 1); i ++) {
				returnarray.push(i);
			}
		} else if(this.currentPage > (this.numPages - this._getCurrentPageIndexInPageLinks())) {
			for(var i = (this.numPages - this.numPageLinks + 1); i < (this.numPages + 1); i++ ) {
				returnarray.push(i);
			}
		} else {
			for(var i = (this.currentPage - this._getCurrentPageIndexInPageLinks()); i < (this.currentPage + this.numPageLinks - this._getCurrentPageIndexInPageLinks()); i ++) {
				returnarray.push(i);
			}
		}
		return returnarray;
	},
	getNext: function() {
		if(this.numPages == this.currentPage) {
			return false;
		}
		return this.currentPage + 1;
	},
	getPrevious: function() {
		if(1 == this.currentPage) {
			return false;
		}
		return this.currentPage - 1;
	},
	getFirstResult: function() {
		return (this.currentPage -1) * this.numPerPage;
	},
	getLastResult: function() {
		var LastResult = this.currentPage * this.numPerPage;
		if(LastResult > this.numResults) {
			return this.numResults;
		} else {
			return LastResult;
		}

	},
	getValuesForLabel: function() {
		//return {'showing-first': this.getFirstResult(), 'showing-last': this.getLastResult}
	}
	
}

function Gadget(){
	//////////////////////////////////////
	// Loader styles
	this.showLoaderFor=function(elem){
		// Hide any errors
		this.hideError();
		Util.addClassNameTo(elem,"loading");
	};
	this.hideLoaderFor=function(elem){
		Util.removeClassNameFrom(elem,"loading");
	};
	//////////////////////////////////////
	// Error methods
	this.onError=function(){};
	this.showError=function(){
		//this.stopFetchTimeout();
		Util.addClassNameTo("ctrGadget","error");
	};
	this.hideError=function(){
		Util.removeClassNameFrom("ctrGadget","error");
	};
	//////////////////////////////////////
	// Set container title
	this.setContainerTitle=function(titleStr) {
		if(_IG_SetTitle)
			_IG_SetTitle(titleStr);
	};
	//////////////////////////////////////
	// Fetch remote content
	this.fetchContent=function(contentType,url,callback,refreshCacheSeconds){
		var _self=this;
		switch(contentType){
			case "text":
				_IG_FetchContent(url,function(response){
					//_self.stopFetchTimeout();
					callback(response)
				});
			break;
			case "xml":
				if(refreshCacheSeconds){
					_IG_FetchXmlContent(url,function(response){
						_self.callBackForXmlFetch(response,callback)
					},{refreshInterval:refreshCacheSeconds});
				}
				else {
					_IG_FetchXmlContent(url,function(response){
						_self.callBackForXmlFetch(response,callback)
					});
				}
			break;
			case "json":
				_IG_FetchFeedAsJSON(url,function(response){
					_self.callBackForJsonFetch(response,callback);
				},10,true);
			break;
		}
	};
	this.callBackForJsonFetch=function(feed,callback){
		//this.stopFetchTimeout();
		if(!feed.Entry || feed==null)
			this.onError("No results found.");
		else
			callback(response);
	};
	this.callBackForXmlFetch=function(response,callback){
		//this.stopFetchTimeout();
		if(response==null || typeof(response)!="object" || response.firstChild==null)
			this.onError("Invalid data.");
		else
			callback(response);
	};
	//////////////////////////////////////
	// Resize functions
	this.resizeTo=function(height,onResized) {
		if(height)
			document.getElementById("ctrGadget").style.height=height+"px";
		window.setTimeout("_IG_AdjustIFrameHeight()",10);
		if(onResized)
			window.setTimeout(onResized,700);
	};
	this.fitToContent=function(onResized) {
		this.resizeTo(null,onResized);
	};
	//////////////////////////////////////
	// Embed flash
	this.embedFlash=function(_url,_container,_opts){
		_IG_EmbedFlash(_url,_container,_opts);
	}
	//////////////////////////////////////
	// Init Gadget object
	// - fire Gadget.onLoaded when loaded
	this.onLoaded=function(){};
	this.init=function() {
		var _self=this;
		_IG_RegisterOnloadHandler(function(){_self.onLoaded()});
	};
	this.init();
}

var PLAYLISTCOUNT;
function buildVideosArray () {
	// Reset global playlist count
	PLAYLISTCOUNT = 0;
	for (var playlist in PLAYLISTS) {
		for (var i = 0; i<PLAYLISTS[playlist].length; i++) {
			loadPlaylistFeed(PLAYLISTS[playlist][i], playlist);
			PLAYLISTCOUNT++;
		}
	}
}

var CACHE = {'cachekeys': [], 'results': [], 'totals': []};
var TotalResults = 0;
var PagingResults = 15;

function getCacheKey(_vq, _sortBy, _direction, _type) {
	var CompletelyReplaced = escape(_vq.replace(' ', '_'));
	while(null != CompletelyReplaced.match(' ')) {
		CompletelyReplaced = CompletelyReplaced.replace(' ', '_');
	}
	var CacheKey = CompletelyReplaced + '_' + _sortBy + '_' + _direction + '_' +_type;
	return CacheKey;
}

function checkCache(CacheKey) {
	for(var i = 0; i < CACHE.cachekeys.length; i++) {
		if(CACHE.cachekeys[i] === CacheKey) {
			return i;
		}
	}
	return false;	
}

function searchVideos(_vq, _sortBy, _direction, _type){
	//check caching
	if(!_sortBy) _sortBy = 'views';
	if(!_direction) _direction = 'desc';
	if(!_type) _type =  null;
	
	SEARCHTERM = _vq;
	switch (ACTIVE) {
		case "fringe":
			SEARCHTERMFRINGE = _vq;
			break;
		case "archive":
			SEARCHTERMARCHIVE = _vq;
			break;
		case "about":
			SEARCHTERMABOUT = _vq;
			break;
	}
	
	var cacheKey = getCacheKey(_vq, _sortBy, _direction, _type);

	// check
	var CacheExists = checkCache(cacheKey);
	if(false !== CacheExists) {		
		Result = CACHE.results[CacheExists];
		TotalResults = CACHE.totals[CacheExists];
	} else {
		Result = [];
		for(var i=0; i < VIDEOS.length; i++) {
			var AddToResult = false;
			if(VIDEOS[i].PlaylistId === _type) {
				if('' == _vq) {
					AddToResult = true;
				} else {
					//check tags if meywords match
					if(VIDEOS[i].Tags) {
						var Tags = VIDEOS[i].Tags.join(' , ');
						// Check if any of the search criteria match and add to resultset
						searchTerms = _vq.toLowerCase().split(" ");
						for (var x=0; x<searchTerms.length; x++) {
							if(Tags.toLowerCase().match(searchTerms[x].toLowerCase())) {
								//MATCHED
								AddToResult = true;
							}
						}
					}
				}
	
				if(AddToResult) {			
					switch(_sortBy) {
						case 'rating':
							if(VIDEOS[i].Rating && VIDEOS[i].Rating.Score) {
								var SortByValue = parseInt(VIDEOS[i].Rating.Score);
							} 
							break;
						case 'duration':
							if(VIDEOS[i].Duration) {
								var SortByValue = parseInt(VIDEOS[i].Duration);
							} 
							break;
						case 'date':
							if(VIDEOS[i].AddedDate) {
								//take the first 10 chars
								var DateBit = VIDEOS[i].AddedDate.substring(0, 10);
								DateBit = DateBit.replace('-', ' ');
								DateBit = DateBit.replace('-', ' ');
								var SortByValue = Date.parse(DateBit);
							}
							break;
						case 'views':
						default:
							if(VIDEOS[i].ViewCount) {
								var SortByValue = parseInt(VIDEOS[i].ViewCount);
							} 
							break;
					}
					if(!SortByValue) {
						var SortByValue = 'Unknown';
					}
					Result.push([SortByValue, VIDEOS[i]]);
				}
			}		
		}
		
		// Handle Caching
		Result =  sortResult(Result, _direction);
		CACHE.cachekeys.push(cacheKey);
		CACHE.results.push(Result);
		TotalResults = Result.length;
		CACHE.totals.push(TotalResults);
	}
	
	// Limit Resultset
/*	var LimitReturn = [];
	for(var i = _limitStart; i < (_limitStart + _howMany); i ++) {
		if(Result[i]) {
			LimitReturn.push(Result[i]);
		} else {
			break;
		}
	}*/
	return Result;
}

function sortVideo(a, b) {
	return a[0] - b[0];
}

function sortResult(Result, Direction) {
	Sorted = Result.sort(sortVideo);
	if('desc' == Direction) {
		Sorted = Sorted.reverse();
	}
	return Sorted;
}

// Convert seconds to minutes
function convertSeconds(secs) {
	secVar0 = secs;                            // The initial data, in seconds
	var minVar = Math.floor(secVar0/60);  // The minutes
	var secVar = secVar0 % 60;              // The balance of seconds
	switch (minVar.toString().length) 
	{
		case 0:
			mins = "00";
		break;
		case 1:
			mins = "0" + minVar;
		break;
		default:
			mins = minVar;
		break;
	}
	switch (secVar.toString().length) 
	{
		case 0:
			secs = "00";
		break;
		case 1:
			secs = "0" + secVar;
		break;
		default:
			secs = secVar;
		break;
	}
	return mins + ":" + secs;
}

// Display Rating
function displayRating(rating){
	switch(Math.round(rating))
	{
		case 0:
			rating = "videoRating-0-0";
		break;
		case 1:
			rating = "videoRating-1-0";
		break;
		case 2:
			rating = "videoRating-2-0";
		break;
		case 3:
			rating = "videoRating-3-0";
		break;
		case 4:
			rating = "videoRating-4-0";
		break;
		case 5:
			rating = "videoRating-5-0";
		break;
	}
	return rating;
}

// Display Rating
function displayMainRating(rating){
	switch(Math.round(rating))
	{
		case 0:
			rating = "mainRating-0-0";
		break;
		case 1:
			rating = "mainRating-1-0";
		break;
		case 2:
			rating = "mainRating-2-0";
		break;
		case 3:
			rating = "mainRating-3-0";
		break;
		case 4:
			rating = "mainRating-4-0";
		break;
		case 5:
			rating = "mainRating-5-0";
		break;
	}
	return rating;
}

function getPlaylistUrl(_playlistId){
	if(_playlistId){
		if(_playlistId.match(/-Comedy-/))
			return "http://gdata.youtube.com/feeds/api/videos?category=%7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007%2Fcategories.cat%7DComedy&orderby=viewCount&max-results=50";
		else
			return "http://gdata.youtube.com/feeds/api/playlists/"+_playlistId + "?max-results=50";
	}
	else
		return false;
}

function loadPlaylistFeed(_playlistId, playlist){
	var _playlistUrl=getPlaylistUrl(_playlistId);
	if(_playlistUrl){
		Gadget.fetchContent("xml", _playlistUrl, function(_feed){
			extractFeedInfo(_feed, function(_index){
				//console.log(PLAYLISTCOUNT);
				if(--PLAYLISTCOUNT === 0) {
					displayHome();
				}
			}, playlist)
		});
	}
}

function extractFeedInfo(_feed,_callback, playlist){
	// Temp object
	//Get playlist id nodes
	PlaylistId = playlist;
	// Get playlist author (ie. venue)
	var _playlistAuthorNodes = getTag(_feed, "author")[0].childNodes;
	for(var j=0; j<_playlistAuthorNodes.length; j++){
		switch(_playlistAuthorNodes[j].nodeName){
			case "name":
				PlaylistVenue=_playlistAuthorNodes[j].firstChild.nodeValue;
			break;
			case "uri":
				PlaylistVenueUri=_playlistAuthorNodes[j].firstChild.nodeValue;
			break;
		}
	}
	var _videoEntries = getTag(_feed, "entry");
	for(var i=0; i<_videoEntries.length; i++){
		var _thisVid={};
		
		_thisVid.Venue = PlaylistVenue;
		_thisVid.VenueUri = PlaylistVenueUri;
		_thisVid.PlaylistId = PlaylistId;
		// Get ID
		_thisVid.Id = getTag(_videoEntries[i], "media:player")[0].getAttribute("url").split("?v=")[1];
		// Get author
		var _authorNodes = getTag(_videoEntries[i], "author")[0].childNodes;
		for(var j=0; j<_authorNodes.length; j++){
			switch(_authorNodes[j].nodeName){
				case "name":
					_thisVid.Author=_authorNodes[j].firstChild.nodeValue;
				break;
				case "uri":
					_thisVid.AuthorUri=_authorNodes[j].firstChild.nodeValue;
				break;
			}
		}
		// Get duration
		_thisVid.Duration = getTag(_videoEntries[i], "yt:duration")[0].getAttribute("seconds");
		// Get rating
		if(getTag(_videoEntries[i], "gd:rating")[0]){
			var _ratingAttrs = getTag(_videoEntries[i], "gd:rating")[0].attributes;
			_thisVid.Rating={};
			for(var k=0; k<_ratingAttrs.length; k++){
				switch(_ratingAttrs[k].nodeName){
					case "numRaters":
						if(_ratingAttrs[k].firstChild)
							_thisVid.Rating.TotalRatings=parseInt(_ratingAttrs[k].firstChild.nodeValue);
						else
							_thisVid.Rating.TotalRatings=parseInt(_ratingAttrs[k].nodeValue);
					break;
					case "average":
						_thisVid.Rating.Score=Math.round(_ratingAttrs[k].nodeValue);
					break;
				}
			}
		}
		// Get title
		_thisVid.Title = getTag(_videoEntries[i], "media:title")[0].firstChild.nodeValue;
		// Get thumbnail
		var _thumbnailAttrs = getTag(_videoEntries[i], "media:thumbnail")[0].attributes;
		for(var k=0; k<_thumbnailAttrs.length; k++){
			switch(_thumbnailAttrs[k].nodeName){
				case "url":
					if(_thumbnailAttrs[k].firstChild)
						_thisVid.Thumbnail=_thumbnailAttrs[k].firstChild.nodeValue;
					else
						_thisVid.Thumbnail=_thumbnailAttrs[k].nodeValue;
				break;
			}
		}
		// Get video page
		_thisVid.VideoPageUrl = getTag(_videoEntries[i], "media:player")[0].getAttribute("url");
		// Get video swf
		var _contentNodes = getTag(_videoEntries[i], "media:content");
		for(var k=0; k<_contentNodes.length; k++){
			if(_contentNodes[k].getAttribute("type")=="application/x-shockwave-flash"){
				_thisVid.VideoSwfUrl=_contentNodes[k].getAttribute("url");
			}
		}
		// Check to make sure SwfUrl is defined as a fallback, otherwise chop up the alternate content url and use that!
		if (typeof(_thisVid.VideoSwfUrl) == "undefined") {
			var _contentNodes = getTag(_videoEntries[i], "link");
			for(var k=0; k<_contentNodes.length; k++){
				if(_contentNodes[k].getAttribute("rel")=="alternate"){
					if(_contentNodes[k].getAttribute("type")=="text/html"){
						_url=_contentNodes[k].getAttribute("href");
						_url = _url.replace("watch?v=", "v/");
						_thisVid.VideoSwfUrl=_url;
						break;
					}
				}
			}
		}
		
		// Get description
		_thisVid.Description = getTag(_videoEntries[i], "media:description")[0].firstChild.nodeValue;
		// Get added date
		if(getTag(_videoEntries[i], "published")[0])
			_thisVid.AddedDate = getTag(_videoEntries[i], "published")[0].firstChild.nodeValue;
		else
			_thisVid.AddedDate = getTag(_videoEntries[i], "updated")[0].firstChild.nodeValue;
		// Get tags (array)
		_thisVid.Tags = getTag(_videoEntries[i], "media:keywords")[0].firstChild.nodeValue.split(", ");
		// Get view count
		_thisVid.ViewCount = parseInt(getTag(_videoEntries[i], "yt:statistics")[0].getAttribute("viewCount"));
		// Get comment count
		if(getTag(_videoEntries[i], "gd:comments")[0]){
			var _commentNodes = getTag(_videoEntries[i], "gd:comments")[0].childNodes;
			for(var j=0; j<_commentNodes.length; j++){
				switch(_commentNodes[j].nodeName){
					case "gd:feedLink":
						_thisVid.CommentCount=_commentNodes[j].getAttribute("countHint");
					break;
				}
			}
		}
		else
			_thisVid.CommentCount=1;
		// Get video response count - TO DO!!
		_thisVid.VideoResponseCount=0;
		
		// Add to videos array
		VIDEOS.push(_thisVid);
	}
	
	if(_callback)
		_callback();
}

function showVideoDetail(_index){
	_gel("video_player").innerHTML="";
	hideContent();
	hideSearchBar();
	renderViewBar();
	hideFooter();
	Util.toggleDisplay("video_player", "block");
	var _player = _gel("video_player");

	// Set gotoVideo Link
	_gel("gotoVideoLink").href=_index.VideoPageUrl;
	
	// Write Video Milarky
	var _mainVideo = document.createElement("div");
	_mainVideo.className="display-mainVideo";
	_mainVideo.id="video";
	_player.appendChild(_mainVideo);
	Gadget.embedFlash(_index.VideoSwfUrl, "video", {flashvars:"autoplay=1&amp;rel=0",wmode:"transparent"});
	
	var _mainDetails = document.createElement("div");
	_mainDetails.className="display-mainDetail";
		_videoDesc = document.createElement("div");
		_videoDesc.className="mainVideo-desc dottedUndeline";						
			//Append Title
			_videoTitle=document.createElement("h1");
			_videoTitle.innerHTML=_index.Title;
			_videoDesc.appendChild(_videoTitle);
			// Append Description
			_videoDescription=document.createElement("p");
			_videoDescription.innerHTML=_index.Description.substr(0,500) + "...";
			_videoDesc.appendChild(_videoDescription);
		_mainDetails.appendChild(_videoDesc);
		_videoMainDetails = document.createElement("div");
		_videoMainDetails.className="mainVideo-details";					
			// Append Heading
			_videoDetailsTitle=document.createElement("h2");
			_videoDetailsTitle.innerHTML="Video Details";
			_videoMainDetails.appendChild(_videoDetailsTitle);
			/*//Append Date Added
			_detailRowAdded = document.createElement("div");
			_detailRowAdded.className="detail-labelRow";
			_videoMainDetails.appendChild(_detailRowAdded);
				_detailRowAddedText = document.createElement("div");
				_detailRowAddedText.className="greyText detailLabel";
				_detailRowAddedText.innerHTML="Added: ";
				_detailRowAdded.appendChild(_detailRowAddedText);
				_detailRowAddedValue = document.createElement("span");
				_detailRowAddedValue.innerHTML=Util.dateDiff(_index.AddedDate);
				_detailRowAdded.appendChild(_detailRowAddedValue);*/					
			// Append Author
			_detailRowFrom = document.createElement("div");
			_detailRowFrom.className="detail-labelRow linkBold";
			_videoMainDetails.appendChild(_detailRowFrom);
				_detailRowFromText = document.createElement("div");
				_detailRowFromText.className="greyText detailLabel";
				_detailRowFromText.innerHTML="From: ";
				_detailRowFrom.appendChild(_detailRowFromText);
				_detailRowFromA = document.createElement("a");
				_detailRowFromA.href="http://youtube.com/user/" + _index.Author;
				_detailRowFromA.innerHTML = _index.Author;
				_detailRowFrom.appendChild(_detailRowFromA);							
			// Append Venue
			_detailRowVenue = document.createElement("div");
			_detailRowVenue.className="detail-labelRow linkBold";
			_videoMainDetails.appendChild(_detailRowVenue);
				_detailRowVenueText = document.createElement("div");
				_detailRowVenueText.className="greyText detailLabel";
				_detailRowVenueText.innerHTML="Venue: ";
				_detailRowVenue.appendChild(_detailRowVenueText);
				_detailRowVenueA = document.createElement("a");
				_detailRowVenueA.href="http://youtube.com/user/" + _index.Venue;
				_detailRowVenueA.innerHTML = _index.Venue;
				_detailRowVenue.appendChild(_detailRowVenueA);
			// Append Tags
			_detailRowTags = document.createElement("div");
			_detailRowTags.className="detail-labelRow";
			_videoMainDetails.appendChild(_detailRowTags);
				_detailRowTagsText = document.createElement("div");
				_detailRowTagsText.className="greyText detailLabel";
				_detailRowTagsText.innerHTML="Tags: ";
				_detailRowTags.appendChild(_detailRowTagsText);
				_detailRowTagsItems = document.createElement("div");
				_detailRowTagsItems.className="detailTagCol";
				_detailRowTags.appendChild(_detailRowTagsItems);
				for (var t = 0; t<_index.Tags.length; t++) { // Loop and display each tag
					_detailRowTagsItem = document.createElement("a");
					_detailRowTagsItem.innerHTML = _index.Tags[t];
					_detailRowTagsItem.href="http://www.youtube.com/results?search_query=" + _index.Tags[t];
					_detailRowTagsItem.target="_blank";
					_detailRowTagsItems.appendChild(_detailRowTagsItem);
				}
			_clear=document.createElement("div");
			_clear.className="clear";
			_videoMainDetails.appendChild(_clear);
		_mainDetails.appendChild(_videoMainDetails);
		// Video Ratings
		_mainVideo_ratings = document.createElement("div");
		_mainVideo_ratings.className="mainVideo-ratings";
			// Append Label
			_mainVideo_ratingLabel = document.createElement("div");
			_mainVideo_ratingLabel.className="ratingLabel";
			_mainVideo_ratingLabel.innerHTML="Rate: ";
			_mainVideo_ratings.appendChild(_mainVideo_ratingLabel);
			// Append Rating Stars + View Count
			_mainVideo_rating_starsWrapper = document.createElement("div");
			_mainVideo_rating_starsWrapper.className="rating-starsWrapper";
			_mainVideo_ratings.appendChild(_mainVideo_rating_starsWrapper);
				// Rating
				_mainVideo_ratings_mainRating = document.createElement("div");
				if(_index.Rating)
					_mainVideo_ratings_mainRating.className = "mainRating " + displayMainRating(_index.Rating.Score);
				else
					_mainVideo_ratings_mainRating.className = "mainRating " + displayMainRating("0");
				_mainVideo_rating_starsWrapper.appendChild(_mainVideo_ratings_mainRating);
				// Rating Count
				_mainVideo_rating_ratingCount = document.createElement("div");
				_mainVideo_rating_ratingCount.className="ratingMsg";
				if(_index.Rating)
					_mainVideo_rating_ratingCount.innerHTML= _index.Rating.TotalRatings + " ratings";
				else
					_mainVideo_rating_ratingCount.innerHTML=  "0 ratings";
				_mainVideo_rating_starsWrapper.appendChild(_mainVideo_rating_ratingCount);
			// Append Views
			_mainVideo_views_wrapper = document.createElement("div");
			_mainVideo_views_wrapper.className="viewsWrapper";
			_mainVideo_ratings.appendChild(_mainVideo_views_wrapper);
				_mainVideo_views_label = document.createElement("div");
				_mainVideo_views_label.className="ratingLabel";
				_mainVideo_views_label.innerHTML="Views: ";
				_mainVideo_views_wrapper.appendChild(_mainVideo_views_label);
				_mainVideo_views_span = document.createElement("span");
				_mainVideo_views_span.innerHTML=_index.ViewCount;
				_mainVideo_views_wrapper.appendChild(_mainVideo_views_span);
			_mainDetails.appendChild(_mainVideo_ratings);
		// Insert a clear div
		_ratingsClear=document.createElement("div");
		_ratingsClear.className="clear";				
		_mainVideo_ratings.appendChild(_ratingsClear);
	_player.appendChild(_mainDetails);
}

function addVideoToHome(_video, _img){
	// Create div container
	// Check if on last tr
//	alert("adding");
	var _vidContainer=document.createElement("tr");
	var _vidContent=document.createElement("td");
	if (4 != _img.split("mostwatched_")[1].split(".")[0]) {
		_vidContent.className="dottedUndeline";
	}
		// Append Rank Image
		var _rankImg=document.createElement("div");
		_rankImg.className="most-watchedRate";
		_vidContent.appendChild(_rankImg);
		var _rankImgImage=document.createElement("img");
		_rankImgImage.height="46";
		_rankImgImage.width="42";
		_rankImgImage.src=_img;
		_rankImg.appendChild(_rankImgImage);
	
		// Append Image
		var _imgContainer=document.createElement("div");
		_imgContainer.className="videoThumbnail";
		_vidContent.appendChild(_imgContainer);
		var _vidThumbnailLink=document.createElement("a");
		_vidThumbnailLink.href="#";
		_vidThumbnailLink.title=_video.Title;
		_vidThumbnailLink.onclick=function(){
		      showVideoDetail(_video);
		      return false;
		};
		var _vidThumbnail = document.createElement("img");
		_vidThumbnail.src=_video.Thumbnail;
		_vidThumbnail.alt=_video.Title;
		_vidThumbnailLink.appendChild(_vidThumbnail);
		_imgContainer.appendChild(_vidThumbnailLink);
          
	      // Append Clip Information
	      var _vidDetails=document.createElement("div");
	      _vidDetails.className="videoDetails";
	          
	          // Append Title
	          var _vidTitleDiv=document.createElement("div");
	          _vidTitleDiv.className="videoTitle";
	          _vidTitleDiv.style.zoom = '1';
	          var _vidTitleH3=document.createElement("h3");
	              var _vidTitle=document.createElement("a");
	              _vidTitle.title=_video.Title;
	              _vidTitle.className="title";
	              _vidTitle.href="#";
	              _vidTitle.onclick=function(){
	                      showVideoDetail(_video);
	                      return false;
	              };
	     		  _vidTitle.innerHTML=_video.Title.substr(0,16) + "...";
	              _vidTitleH3.appendChild(_vidTitle);
	          _vidTitleDiv.appendChild(_vidTitleH3);
	          _vidDetails.appendChild(_vidTitleDiv);
	          
	          // Append Author
	          var _vidAuthorDiv=document.createElement("div");
	          _vidAuthorDiv.className="videoFromTag";
				  var _vidAuthorFrom=document.createElement("span");
	              _vidAuthorFrom.className="greyText";
	              _vidAuthorFrom.innerHTML="From: ";
	              _vidAuthorDiv.appendChild(_vidAuthorFrom);
	              var _vidAuthor=document.createElement("a");
	              _vidAuthor.className="author";
	              _vidAuthor.href="http://youtube.com/user/" + _video.Author;
	              _vidAuthor.target="_blank";
	              _vidAuthor.innerHTML=_video.Author.substr(0, 15);
	              _vidAuthorDiv.appendChild(_vidAuthor);
	          _vidDetails.appendChild(_vidAuthorDiv);
	          
	          // Append Duration
	          var _vidDurationDiv=document.createElement("div");
	          _vidDurationDiv.className="videoTime";
	              var _vidDuration=document.createElement("span");
	              _vidDuration.className="duration";
	              _vidDuration.innerHTML=convertSeconds(_video.Duration);
	              _vidDurationDiv.appendChild(_vidDuration);
	          _vidDetails.appendChild(_vidDurationDiv);
	          
	          // Append Rating
	          var _vidRating=document.createElement("div");
	          if(_video.Rating)
	          	_vidRating.className="videoRating " + displayRating(_video.Rating.Score);
	          else
	          	_vidRating.className="videoRating " + displayRating("0");
	          _vidDetails.appendChild(_vidRating);
	          
	          // Append From Venue
	          var _vidFromDiv=document.createElement("div");
	          _vidFromDiv.className="videoFromTag";
				  var _vidFrom=document.createElement("span");
	              _vidFrom.className="greyText";
	              _vidFrom.innerHTML="More from:<br />";
	              _vidFromDiv.appendChild(_vidFrom);
	              var _vidFromA=document.createElement("a");
	              _vidFromA.className="author";
	              _vidFromA.href="http://youtube.com/user/" + _video.Venue;
	              _vidFromA.target="_blank";
	              _vidFromA.innerHTML=_video.Venue.substr(0, 15);
	              _vidFromDiv.appendChild(_vidFromA);
	          _vidDetails.appendChild(_vidFromDiv);
			             
	      _vidContent.appendChild(_vidDetails);

	_vidContainer.appendChild(_vidContent);
	
	document.getElementById("table_mostwatched").getElementsByTagName('tbody')[0].appendChild(_vidContainer);
	displayHome();
}

function addVideoToBrowser(_video, _target){
	// Create div container
	var _vidContainer=document.createElement("div");
	_vidContainer.className="videoContainer";
          // Append Image
          var _thumbDiv=document.createElement("div");
          _thumbDiv.className="videoThumbnail";
          var _vidThumbnailLink=document.createElement("a");
          _vidThumbnailLink.onclick=function(){
                  showVideoDetail(_video);
                  return false;
          };
          _vidThumbnailLink.href="#";
          _vidThumbnailLink.title=_video.Title;
              var _vidThumbnail = document.createElement("img");
              _vidThumbnail.src=_video.Thumbnail;
              _vidThumbnail.alt=_video.Title;
              _vidThumbnailLink.appendChild(_vidThumbnail);
          _thumbDiv.appendChild(_vidThumbnailLink);
          _vidContainer.appendChild(_thumbDiv);
          
          // Append Clip Information
          var _vidDetails=document.createElement("div");
          _vidDetails.className="videoDetails";
              
              // Append Title
              var _vidTitleDiv=document.createElement("div");
              _vidTitleDiv.className="videoTitle";
              var _vidTitleH3=document.createElement("h3");
              var _vidTitle=document.createElement("a");
              _vidTitle.className="title";
              _vidTitle.href="#";
              _vidTitle.onclick=function(){
                      showVideoDetail(_video);
                      return false;
              };
          if(_video.Title.length>16)
     		  	_vidTitle.innerHTML=_video.Title.substr(0, 16)+"...";
     		  else
     		  	_vidTitle.innerHTML=_video.Title;
     		  _vidTitle.title=_video.Title;
              _vidTitleH3.appendChild(_vidTitle);
              _vidTitleDiv.appendChild(_vidTitleH3);
              _vidDetails.appendChild(_vidTitleDiv);
             
              // Append Author
              var _vidAuthorDiv=document.createElement("div");
              _vidAuthorDiv.className="videoFromTag";
				  var _vidAuthorFrom=document.createElement("span");
	              _vidAuthorFrom.className="greyText";
	              _vidAuthorFrom.innerHTML="From: ";
	              _vidAuthorDiv.appendChild(_vidAuthorFrom);
	              var _vidAuthor=document.createElement("a");
	              _vidAuthor.className="author";
	              _vidAuthor.href="http://youtube.com/user/" + _video.Author;
	              _vidAuthor.target="_blank";
	              _vidAuthor.innerHTML=_video.Author.substr(0, 15);
	              _vidAuthorDiv.appendChild(_vidAuthor);
              _vidDetails.appendChild(_vidAuthorDiv);
              
              // Append Duration
              var _vidDurationDiv=document.createElement("div");
              _vidDurationDiv.className="videoTime";
	              var _vidDuration=document.createElement("span");
	              _vidDuration.className="duration";
	              _vidDuration.innerHTML=convertSeconds(_video.Duration);
	              _vidDurationDiv.appendChild(_vidDuration);
              _vidDetails.appendChild(_vidDurationDiv);
              
              // Append Rating
              var _vidRating=document.createElement("div");
              if(_video.Rating)
              	_vidRating.className="videoRating " + displayRating(_video.Rating.Score);
              else
              	_vidRating.className="videoRating " + displayRating("0");
              _vidDetails.appendChild(_vidRating);
              
              // Append From Venue
              var _vidFromDiv=document.createElement("div");
              _vidFromDiv.className="videoFromTag";
				  var _vidFrom=document.createElement("span");
	              _vidFrom.className="greyText";
	              _vidFrom.innerHTML="More from:<br />";
	              _vidFromDiv.appendChild(_vidFrom);
	              var _vidFromA=document.createElement("a");
	              _vidFromA.className="author";
	              _vidFromA.href="http://youtube.com/user/" + _video.Venue.substr(0, 15);
	              _vidFromA.target="_blank";
	              _vidFromA.innerHTML=_video.Venue;
	              _vidFromDiv.appendChild(_vidFromA);
              _vidDetails.appendChild(_vidFromDiv);
			             
          _vidContainer.appendChild(_vidDetails);

	// Add html to gadget
	document.getElementById(_target).appendChild(_vidContainer);
}

function getVenueList(){
	var _venues=[];
	for(var i=0; i<VIDEOS.length; i++){
		_venues.push(VIDEOS[i].Venue);
	}
	var _deDupedVenues=[];
        var lastValue="";
        for(var i=0; i<_venues.length; i++){
          var curValue=_venues[i];
          if(curValue!=lastValue)
            _deDupedVenues[_deDupedVenues.length]=curValue;
            lastValue=curValue;
	}
	return _deDupedVenues;
}

function getTag(context, tag)
{
	if (context.getElementsByTagNameNS && (-1 != tag.indexOf(':')))
	{
		var tagArray = tag.split(':');
		tag = tagArray[tagArray.length-1];
		return context.getElementsByTagNameNS('*', tag);
	}
	
	return context.getElementsByTagName(tag);
}